<template>
  <div class="login-container">
    <div class="back">
      <p id="name_panle">学生成绩积分系统</p>
      <el-form class="login-box" :rules="rulers" :model="user">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="user.name" placeholder="手机号 / 用户名 / 邮箱"
            @keydown.enter.native="handleLogin" @input="saveUser()"></el-input>
        </el-form-item>
        <el-form-item prop="password" style="margin-bottom: 0;">
          <el-input prefix-icon="el-icon-lock" type="password" :show-password="true" v-model="user.password"
            placeholder="密码" @keydown.enter.native="handleLogin" @input="saveUser()"></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input v-model="user.captcha" placeholder="请输入验证码" @input="saveUser()"
              @keydown.enter.native="handleLogin"></el-input>
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaImage" alt="验证码" />
            </div>
          </div>
        </el-form-item>
        <el-form-item style="margin-bottom: 0;">
          <el-button :loading="loading" @click="handleLogin" :disabled="!isFormValid">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import router from '@/router';
import { getUserLocation } from '@/utils/locationUtils';
import { loginURL, logURL } from '@/utils/urlManager';
import '@/utils/InterceptorUtils'
import axios from 'axios';
export default {
  name: 'LoginView',
  data() {
    return {
      user: {
        userId: '',
        name: '',
        password: '',
        email: '',
        place: '',
        captcha: '' // 新增验证码字段
      },
      errorMsg: '',
      loading: false,
      rulers: {
        username: [
          // { required: true, message: '请输入用户名', trigger: 'blur' },
          // { min: 3, max: 15, message: '长度在 3 到 10 个字符之间', trigger: 'change' }
        ],
        password: [
          // { required: true, message: '请输入密码', trigger: 'blur' },
          // { min: 6, max: 10, message: '长度在 6 到 10 个字符之间', trigger: 'change' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '验证码长度为4位', trigger: 'change' }
        ]
      },
      login_url: '',
      captchaImage: '' // 用于存储验证码图片的URL
    };
  },
  computed: {
    isFormValid() {
      if (this.user.name != null && this.user.password != null && this.user.captcha != null)
        if (this.user.name.length > 0 && this.user.password.length > 0 && this.user.captcha.length === 4)
          return this.user.name.trim() !== '' && this.user.password.trim().length >= 6 && this.user.captcha.trim().length === 4;
    }
  },
  methods: {
    /**
     * 用户登录函数
     */
    handleLogin() {
      this.loading = true;
      if (!this.user.captcha || this.user.captcha !== this.captchaAnswer) {
        this.$message.warning('验证码错误');
        this.refreshCaptcha();
        this.loading = false;
        return;
      }

      switch (this.user.role) {
        case 1:
          this.login_url = "student";
          break;
        case 2:
          this.login_url = "teacher";
          break;
        case 3:
          this.login_url = "admin";
          break;
      }
      axios.post(loginURL, this.user)
        .then((response) => {
          const state = response.data.data;
          localStorage.setItem("role", this.login_url);
          if (state != null) {
            localStorage.setItem('Authorization', response.data.data.token);
            localStorage.setItem('role', response.data.data.roleId);
            router.push('/front');
            this.$message.success("登录成功！");
            localStorage.setItem("unCompleteData", "");
            localStorage.setItem("homeworkData", "");
            // console.log(response);
            this.addLog()
            // myLog("登录")
          } else {
            this.$message.warning(response.data.msg);
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
          this.errorMsg = err;
          this.$message.warning(err);
        })
    },
    /**
     * 实时存储登录user信息
     */
    saveUser() {
      let userJSON = JSON.stringify(this.user);
      localStorage.setItem('user', userJSON);
    },
    /**
     * 自动填充user信息
     */
    fillUser() {
      let userJSON = localStorage.getItem('user');
      if (userJSON) {
        try {
          let userObj = JSON.parse(userJSON);
          userObj.captcha = "";
          this.user = userObj;
        } catch (error) {
          console.error('Error parsing user JSON:', error);
          this.user = {}; // 设置一个默认值，避免页面崩溃
        }
      } else {
        this.user = {}; // 如果没有 user 数据，设置一个默认值
      }
    },
    /**
     * 生成验证码
     */
    generateCaptcha() {
      const chars = 'abcdefghjkmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 4; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.captchaAnswer = result;
      this.captchaImage = `data:image/png;base64,${this.createCaptchaImage(result)}`;
    },
    /**
     * 刷新验证码
     */
    refreshCaptcha() {
      this.generateCaptcha();
    },
    /**
     * 创建验证码图片
     */
    createCaptchaImage(text) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = 100;
      canvas.height = 40;

      // 背景颜色
      ctx.fillStyle = '#eeeeee';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 文字颜色
      ctx.fillStyle = '#333333';
      ctx.font = '20px Arial';
      ctx.textBaseline = 'middle';
      ctx.textAlign = 'center';

      // 绘制验证码文字
      for (let i = 0; i < text.length; i++) {
        ctx.fillText(text[i], 25 * i + 10, canvas.height / 2);
      }

      // 添加干扰线
      for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = '#cccccc';
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
      }

      // 添加干扰点
      for (let i = 0; i < 30; i++) {
        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
        ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2);
      }

      // 转换为base64
      return canvas.toDataURL().replace('data:image/png;base64,', '');
    },
    addLog() {
      getUserLocation()
        .then((location) => {
          const place = location.province + location.city
          const params = {
            behavior: "登录", 
            place: place
          }
          // console.log('获取到的地理位置信息:', location);
          axios.put(logURL,null, {params})
        })
        .catch((error) => {
          console.error('获取地理位置信息失败:', error);
        });
    }
  },
  mounted() {
    this.fillUser();
    this.generateCaptcha(); // 初始化验证码
  }
};
</script>

<style scoped>
/* 电脑端页面 */
@media screen and (min-width: 768px) {
  #name_panle {
    font-size: 5vw;
    height: 40vh;
    margin: 0;
    display: flex;
    align-items: center;
  }

  .login-container {
    height: 100vh;
    width: 100vw;
    background-image: url("../../assets/background/background.png");
    background-size: cover;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .back {
    height: 100%;
    width: 100%;
    background-color: rgb(255, 255, 255, 0.80);
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .login-box {
    background: rgba(255, 255, 255, 0.2);
    padding: 2vw;
    width: 20vw;
    border-radius: 1vw;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .login-box p {
    padding: 0;
    margin: 0;
    background: rgba(255, 255, 255, 0.2);
  }

  .el-button {
    margin-top: 10px;
    width: 100%;
    padding: 10px;
    border: none;
    border-radius: 4px;
    background-color: #5cb85c;
    color: white;
    cursor: pointer;
    opacity: 1;
    transition: opacity 0.3s;
  }

  .el-button:disabled {
    opacity: 0.5;
  }

  .el-button:hover {
    background-color: #4cae4c;
  }

  .captcha-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .captcha-image {
    cursor: pointer;
    margin-left: 10px;
  }

  .captcha-image img {
    width: 100px;
    height: 40px;
    border-radius: 4px;
  }
}

/* 手机端页面 */
@media screen and (max-width: 768px) {
  .login-container {
    height: 100vh;
    width: 100vw;
    background-image: url("../../assets/background/background1.jpg");
    background-size: cover;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .login-box {
    background: rgba(255, 255, 255, 0.8);
    padding: 5vw;
    width: 90vw;
    border-radius: 5vw;
    margin-top: -20vh;
  }

  #name_panle {
    font-size: 4vh;
    height: 40vh;
    margin: 0;
    padding: 12vw;
    display: flex;
    color: rgb(255, 255, 255);
  }

  .captcha-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .captcha-image {
    cursor: pointer;
    margin-left: 10px;
  }

  .captcha-image img {
    width: 100px;
    height: 40px;
    border-radius: 4px;
  }
}
</style>